<form class="layui-form seller-form"  action="" >
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年度：</label>
            <div class="layui-input-inline">
                <select name="year" lay-filter="draw_year" id="draw_year" lay-search>
                    <option value=""></option>
                    {volist name="yearList" id="yearList"}
                    <option value="{$yearList.id}">{$yearList.year}</option>
                    {/volist}
                </select>
            </div>
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">季度：</label>
            <div class="layui-input-inline">
                <select name="season" lay-filter="draw_season" id="draw_season" lay-search>
                    <option value=""></option>
                    {volist name="seasonList" id="seasonList"}
                    <option value="{$seasonList.season_id}">{$seasonList.season_name}</option>
                    {/volist}
                </select>
            </div>	
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">部/院：</label>
            <div class="layui-input-inline">
                <select name="dep_id" lay-filter="draw_dep_id" id="draw_dep_id" lay-search>
                    <option value=""></option> 
                    {volist name="deptList" id="deptList"}
                    <option value="{$deptList.bmdm}">{$deptList.bmmc}</option>
                    {/volist} 
                </select>
            </div>	
        </div>	
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">年级：</label>
            <div class="layui-input-inline">
                <select name="plan_grade" lay-filter="plan_grade" id="plan_grade" lay-search>
                    <option value=""></option> 
                    {volist name="gradeList" id="gradeList"}
                    <option value="{$gradeList.plan_grade}">{$gradeList.plan_grade}</option>
                    {/volist} 
                </select>
            </div>	
        </div>	
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">层次：</label>
            <div class="layui-input-inline">
                <select name="plan_degree_id" lay-filter="plan_degree_id" id="plan_degree_id" lay-search>
                    <option value=""></option> 
                    {volist name="degreeList" id="degreeList"}
                    <option value="{$degreeList.plan_degree_id}">{$degreeList.plan_degree_name}</option>
                    {/volist} 
                </select>
            </div>	
        </div>
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">专业：</label>
            <div class="layui-input-inline">
                <select name="specialty_id" lay-filter="draw_specialty_id" id="draw_specialty_id" lay-search>
                </select>
            </div>	
        </div>	
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">班级：</label>
            <div class="layui-input-inline">
                <select name="class_id" lay-filter="draw_class_id" id="draw_class_id" lay-search>
                </select>
            </div>		
        </div>	
        <div class="layui-inline">
            <label class="layui-form-label seller-inline-2">方向：</label>
            <div class="layui-input-inline">
                <select name="dir" lay-filter="draw_dir" id="draw_dir" lay-search>
                    <option value=""></option>
                    {volist name="dirList" id="dirList"}
                    <option value="{$dirList.id}">{$dirList.name}</option>
                    {/volist}
                </select>
            </div>		
        </div>	
    </div>
</form>

<div class="table-body">
    <table id="supplyAddTable" lay-filter="supplyAddTable"></table>
</div>

<script>
    var mgrMobile = '';
    layui.use(['table','form','layer','laydate'],function(){
        var layer = layui.layer, table = layui.table,form = layui.form,date = layui.laydate;
        // 定义变量保存当前页面和当前页面数据条数
        var currPage; 
        var dataNum;

        layui.use('form', function(){
            $("#draw_year").val({$year});  // 年度：
            $("#draw_season").val({$season});  // 季度：
            $("#draw_dir").val(1);  // 默认方向：就业
            layui.form.render();
        });

        //执行渲染
        table.render({
            elem: '#supplyAddTable', //指定原始表格元素选择器（推荐id选择器）
            height: 'full-165',
            cellMinWidth: '80',
            page: 'true',
            limit:'20',
            id:'supplyAddTable',
            url: "{:url('BookDraw/supplyBookList')}",
            toolbar: '#toolbarDemo',
            defaultToolbar: [],
            cols: [[ //标题栏
                {type:'numbers'},
                {field: 'id', title: 'ID', hide:true},
                {field: 'book_id', title: 'BOOK_ID', hide:true},
                {field: 'book_name', title: '教材名称', width:300, align:'center'}, 
                {field: 'book_isbn', title: 'ISBN', align:'center', width: 140},
                {field: 'plan_book_num', title: '教材数量', align:'center', width: 120},
                {field: 'plan_price', title: '单价', align:'center', width: 120},
                {field: 'book_disc', title: '折扣', align:'center', width: 120},
                { width: 120, title: '操作', align: 'center', toolbar: '#hooksBar' }
            ]], //设置表头
            done: function(res, curr, count){
                // 给变量赋值 
                dataNum = res.data.length;
                currPage = curr;
            }
        });

        form.render();

        layui.use('form', function () {
            // 联动年度
            form.on('select(draw_year)', function (data) {
                getClass(data);
            });

            // 联动部门
            layui.form.on('select(draw_dep_id)', function (data) {
                getSpecialty(data);
            });
        
            // 联动专业  
            layui.form.on('select(draw_specialty_id)', function (data) {
                getClass(data);
            });
            
            // 联动年级 
            layui.form.on('select(plan_grade)', function (data) {
                getClass(data);
            });

            // 联动层次
            layui.form.on('select(plan_degree_id)', function (data) {
                getClass(data);
            });
            
        });

        // 得到专业
        function getSpecialty(data) {
            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getSpecicalties')}",
                data: 'bmdm=' + data.value,
                success: function(e) {
                    if(e.status) {
                        $("#draw_specialty_id").empty();//清空下拉框的值
                        $('#draw_specialty_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $("#draw_class_id").empty();//清空下拉框的值
                        $('#draw_class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#draw_specialty_id').append(new Option(item.zymc, item.zydm));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };
        
        // 得到班级
        function getClass(data) { 
            var year = $("#draw_year").val();
            var season = $("#draw_season").val();
            var dept = $("#draw_dep_id").val();
            var specialty_id = $('#draw_specialty_id').val();
            var plan_grade = $("#plan_grade").val();
            var plan_degree_id = $("#plan_degree_id").val();

            $.ajax({
                type: 'get',
                url: "{:url('BookCommon/getClasses')}",
                data: {
                        "plan_year":  year,
                        "plan_season": season,
                        "bmdm": dept,
                        "zydm": specialty_id,
                        "plan_grade": plan_grade,
                        "plan_degree_id": plan_degree_id
                    },
                success: function(e) {
                    if(e.status) {
                        $("#draw_class_id").empty();//清空下拉框的值
                        $('#draw_class_id').append(new Option('', ''));// 下拉菜单里添加元素
                        $.each(e.data.data, function (index, item) {
                            $('#draw_class_id').append(new Option(item.plan_class_name, item.plan_class_id));// 下拉菜单里添加元素
                        });
                        layui.form.render("select");//重新渲染 固定写法
                    } else {
                        layer.msg(e.msg);
                    }
                }
            });
        };

        //头工具栏事件
        layui.table.on('toolbar(supplyAddTable)', function (obj) {
            switch (obj.event) {
                case 'bookAdd': 
                    $("#bookAdd").addClass("layui-btn-disabled");
                    $("#bookAdd").attr("disabled", true);

                    JsGet("{:url('BookDraw/supplyAddBook')}", function(e){
                        $("#bookAdd").removeClass("layui-btn-disabled");
                        $("#bookAdd").removeAttr("disabled");
                        if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                            layer.msg(e.msg); return false;
                        }

                        window.box = layer.open({
                            type: 1,
                            content: e,
                            area: ['750px', '350px'],
                            title:'增加教材',
                            id: 'LAY_booksupplydraw_addbook'  // 设定id，防止重复弹出
                            ,shadeClose: false
                        });
                    });
                    break;
                case 'bookSupply':  
                    var year = $('#draw_year').val();
                    var season = $('#draw_season').val();
                    var dep_id = $('#draw_dep_id').val();
                    var plan_grade = $('#plan_grade').val();
                    var plan_degree_id = $('#plan_degree_id').val();
                    var specialty_id = $('#draw_specialty_id').val();
                    var class_id = $('#draw_class_id').val();
                    var dir = $('#draw_dir').val();

                    if(layui.table.cache.supplyAddTable.length == 0) {
                        layer.msg('请先增加教材', {time: 1300});
                        return false;
                    }

                    if(!year){
                        layer.msg('年度不能为空！', {time: 1300});
                        return false;
                    }
                    if(!season){
                        layer.msg('季度不能为空！', {time: 1300});
                        return false;
                    }
                    if(!dep_id){
                        layer.msg('部/院不能为空！', {time: 1300});
                        return false;
                    }
                    if(!plan_grade){
                        layer.msg('年级不能为空！', {time: 1300});
                        return false;
                    }
                    if(!plan_degree_id){
                        layer.msg('层次不能为空！', {time: 1300});
                        return false;
                    }

                    layer.confirm('确定要发放吗?', {icon: 3, title:'提示'}, function(){
                        JsPost("{:url('BookDraw/supplydrawsave')}", {'year':year, 'season':season, 'dep_id':dep_id, 'plan_grade':plan_grade, 'plan_degree_id':plan_degree_id, 'specialty_id':specialty_id, 'class_id':class_id, 'dir':dir}, 
                            function(e){
                                if ((e.hasOwnProperty('status') && !e.status) || (e.hasOwnProperty('code') && e.code == 0)) {
                                    layer.msg(e.msg); return false;
                                }
         
                                if(e.status){
                                    layer.open({
                                        type: 1
                                        ,offset: 'auto'
                                        ,id: 'layerDemoAuto'
                                        ,content: '<div style="padding: 20px 100px;">'+ e.msg +'</div>'
                                        ,btn: '关闭'
                                        ,btnAlign: 'c' //按钮居中
                                        ,shade: 0.3 //显示遮罩
                                        ,yes: function(){
                                            layer.closeAll();
                                            var where = {
                                                year : year,
                                                season : season
                                            }
                                            
                                            var control = {
                                                '#supply_index_year': year,
                                                '#supply_index_season': season
                                            }

                                            parent.layui.admin.events.refreshTab('/manage/book_draw/booksupplydrawindex.html', 'booksupplydrawTable', "{:url('BookDraw/booksupplydrawindex')}?year="+year+"&season="+season+"&dep_id=&specialty_id=&class_id=&dir=1&is_dy=0", where, control);
                                        },close: function() {
                                        }
                                    });
                                }else{  
                                    layer.msg(res.msg,{time:1300});
                                }
                            }
                        )
                    });  
                    break;
            };
        });
        
        //监听工具条
        table.on('tool(supplyAddTable)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            
            if(layEvent === 'del'){ //编辑  
                layer.confirm('您确定删除吗？', {
                    btn: ['确认', '取消'] //按钮
                }, function () {
                    JsPost("{:url('BookDraw/supplyDelBook')}", { 'id': data.id }, function(res){
                        //删除逻辑中判断只有一条数据时应该刷新前一页信息
                        layer.msg(res.msg);
                        if(res.status){
                            if(dataNum == 1){
                                currPage = currPage - 1;
                            }

                            table.reload('supplyAddTable', {
                                page: {
                                    curr: currPage
                                }
                            });
                            return false;
                        }
                    });
                }, function () {
                    layer.close(1);
                });
                return false;
            }
        });
    })
</script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" id = "bookAdd" lay-event="bookAdd">增加教材</button>
        <button class="layui-btn layui-btn-sm" id = "bookSupply" lay-event="bookSupply">补发</button>
    </div>
</script>

<script type="text/html" id="hooksBar">
    <a class="layui-btn layui-btn-xs layui-btn-danger" name="del" lay-event="del">删除</a>
</script>